import { _decorator, Component, instantiate, Node } from 'cc';
import { ResMgr } from '../Mgr/ResMgr';
import { AssetList } from '../Global';
import { GameScene } from './GameScene';
import { BattleCard } from './BattleCard';
import { LocalStorageMgr } from '../Mgr/LocalStorageMgr';
import { DisCard } from './DisCard';
const { ccclass, property } = _decorator;

@ccclass('CardLoad')
/**
 * 攻击层
 */
export class CardLoad extends Component {

    //手牌数组
    public CardArray: Node[] = [];

    //没用得卡牌
    public Nouse: Node[] = [];

    protected start(): void {

    }

    /**
     * 获取卡牌
     */
    public GetCard() {
        let card: Node = null;
        if (this.Nouse.length == 0) {
            card = instantiate(ResMgr.Instance.Prefabs[AssetList.Prefabs.BattleCard]);
        } else {
            card = this.Nouse.shift();
            card.active = true;
        }
        this.node.addChild(card);
        this.CardArray.push(card);

        let ran_num: number = Math.floor(Math.random() * GameScene.Instance.BattleCardInfo.length);
        card.getComponent(BattleCard).UpdateCard(GameScene.Instance.BattleCardInfo[ran_num])
        GameScene.Instance.BattleCardInfo.splice(ran_num, 1);
    }

    /**
     * 判断是否添加卡牌
     */
    public CheckAddCard() {
        if (this.CardArray.length != 0) return;

        let is_dis: boolean = false;

        if (GameScene.Instance.DisCard.active) {
            is_dis = GameScene.Instance.DisCard.getComponent(DisCard).Card.active
        }

        //判断游戏结束
        if (GameScene.Instance.BattleCardInfo.length == 0 && !is_dis) {
            LocalStorageMgr.Instance.LOCAL_STORAGE_DATA.FAIL++;
            LocalStorageMgr.Instance.UpdateLocalStroage();
            GameScene.Instance.GameOver();
            return;
        }

        let hand_num: number = GameScene.Instance.HandNum;

        if (GameScene.Instance.BattleCardInfo.length < hand_num) hand_num = GameScene.Instance.BattleCardInfo.length;

        for (let i = 0; i < hand_num; i++) {
            this.GetCard();
        }

        for (let i = 0; i < this.CardArray.length; i++) {
            this.CardArray[i].getComponent(BattleCard).PlayGiveCardAni(i);
        }

        GameScene.Instance.UpdateCardNum();

    }

    /**
     * 卡牌消失
     */
    public CardDisappear(card: Node) {
        this.Nouse.push(card);
        card.active = false;
        this.CardArray.splice(this.CardArray.indexOf(card), 1);
        this.CheckAddCard();
    }

}


